package com.qcby.demo.proxyaop.chain;

import com.qcby.demo.proxyaop.interceptor.Interceptor;
import com.qcby.demo.proxyaop.interceptor.QcbyInterceptor;
import com.qcby.demo.proxyaop.proxy.star.JiaLing;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @className: InterceptorHandler
 * @description: 经纪人拦截器的动态代理类
 * @author: lxt
 * @create: 2021-05-12 16:07
 **/
public class ChainInterceptorHandler implements InvocationHandler {

    //代理逻辑内添加一个真实对象的引用，从而实现代理逻辑与真实对象的绑定
    private Object target = null;


    //现在的代理逻辑类加入了一个我们设计好的拦截器，用来更好地帮我们丰富代理逻辑
    private Interceptor interceptor = null;


    //绑定真实对象和拦截器
    public ChainInterceptorHandler(Object target, Interceptor interceptor) {
        this.target = target;
        this.interceptor = interceptor;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (interceptor == null) {
            //如果没有给代理逻辑类配置一个拦截器的话，则直接反射真实对象的方法
            return method.invoke(target, args);
        }
        Object r = null;
        try {
            if (!interceptor.preHandle(proxy, target, method, args)) {
                return r;
            }
            r = method.invoke(target, args);
            //目标方法执行完毕，后处理
            interceptor.postHandle(proxy, target, method, args);
        }catch (Exception e){
            // 打印堆栈跟踪信息
            e.printStackTrace();
        }finally {
            //一定会被调用
            interceptor.afterCompletion(proxy, target, method, args);
        }
        return r;
    }
}
